<template>
  <div class="marketing-video-audio">
    <!-- 顶部进度条 -->
    <div class="progress-bar">
      <div class="step-item completed">
        <div class="step-number">1</div>
        <div class="step-text">选择一个数字人并上传一张产品图片</div>
      </div>
      <div class="step-item active">
        <div class="step-number">2</div>
        <div class="step-text">编辑营销文案</div>
      </div>
      <div class="step-item">
        <div class="step-number">3</div>
        <div class="step-text">生成视频</div>
      </div>
      <div class="step-item">
        <div class="step-number">4</div>
        <div class="step-text">完成</div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧选择的数字人和产品展示 -->
      <div class="left-panel">
        <div class="selected-info">
          <h3>已选择的内容</h3>
          <div class="info-cards">
            <div class="info-card">
              <h4>数字人</h4>
              <div v-if="selectedAvatar" class="avatar-preview">
                <img :src="selectedAvatar.imageUrl" :alt="selectedAvatar.name" />
                <span>{{ selectedAvatar.name }}</span>
              </div>
              <div v-else class="no-selection">
                <span>未选择数字人</span>
                <el-button type="text" @click="goBack">返回选择</el-button>
              </div>
            </div>
            <div class="info-card">
              <h4>产品图片</h4>
              <div v-if="selectedImage" class="image-preview">
                <img :src="selectedImage.url" alt="产品图片" />
              </div>
              <div v-else class="no-selection">
                <span>未选择产品图片</span>
                <el-button type="text" @click="goBack">返回选择</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧脚本编辑面板 -->
      <div class="script-panel">
        <div class="script-header">
          <h3>脚本编辑</h3>
          <el-button-group>
            <el-button 
              :type="scriptMode === 'tts' ? 'primary' : 'default'" 
              @click="scriptMode = 'tts'"
            >
              文本转语音
            </el-button>
            <el-button 
              :type="scriptMode === 'audio' ? 'primary' : 'default'" 
              @click="handleSwitchToAudio"
            >
              导入音频
            </el-button>
          </el-button-group>
        </div>
        
        <!-- 文本转语音模式 -->
        <template v-if="scriptMode === 'tts'">
          <el-input
            type="textarea"
            :rows="20"
            placeholder="在此输入需要AI配音的文本..."
            v-model="scriptText"
            maxlength="8000"
            show-word-limit
            class="script-textarea"
          />
        </template>

        <!-- 导入音频模式 -->
        <template v-else>
          <div class="audio-upload-section">
            <input
              type="file"
              accept="audio/*"
              class="file-input"
              ref="audioInputRef"
              @change="handleAudioSelect"
            />
            <div v-if="!previewAudio" class="upload-placeholder" @click="triggerAudioSelect">
              <el-icon size="32"><Upload /></el-icon>
              <div class="upload-text">点击上传音频文件</div>
              <div class="upload-hint">支持 MP3, WAV 等格式</div>
            </div>
            <div v-else class="audio-preview">
              <div class="audio-info">
                <el-icon><Document /></el-icon>
                <span class="audio-name">{{ previewAudio.fileName }}</span>
              </div>
              <audio controls :src="previewAudio.url" class="audio-player"></audio>
              <div class="audio-actions">
                <el-button type="danger" @click="resetAudioUpload">重新上传</el-button>
              </div>
            </div>
          </div>
        </template>

        <div class="script-footer">
          <el-select
            v-if="scriptMode === 'tts'"
            v-model="selectedVoice"
            placeholder="选择AI音色"
            class="voice-select"
          >
            <el-option
              v-for="voice in voiceList"
              :key="voice.voiceId"
              :value="voice"
              :label="voice.voiceName"
            />
          </el-select>
          <el-select v-model="subtitleStyle" placeholder="字幕样式" class="subtitle-select">
            <el-option label="无字幕" value="" />
            <el-option label="标准字幕" value="standard" />
            <el-option label="创意字幕" value="creative" />
          </el-select>
          <div class="action-buttons">
            <el-button @click="goBack">上一步</el-button>
            <el-button 
              type="primary" 
              :disabled="!canProceed"
              @click="handleGenerateVideo"
            >
              <el-icon><VideoPlay /></el-icon>
              生成视频
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Upload, Document, VideoPlay } from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import { apiRequest, API_CONFIG } from '../../config/api.js'
import axios from 'axios'

const router = useRouter()

// 数据
const scriptMode = ref('tts')
const scriptText = ref('')
const selectedVoice = ref(null)
const subtitleStyle = ref('')
const previewAudio = ref(null)
const audioInputRef = ref(null)
const selectedAvatar = ref(null)
const selectedImage = ref(null)
const voiceList = ref([])

// 计算属性：是否可以进行下一步
const canProceed = computed(() => {
  if (scriptMode.value === 'tts') {
    return scriptText.value.trim() && selectedVoice.value
  } else {
    return previewAudio.value
  }
})

// 切换到音频模式
const handleSwitchToAudio = () => {
  scriptMode.value = 'audio'
  scriptText.value = '' // 清空文本
}

// 触发音频选择
const triggerAudioSelect = () => {
  audioInputRef.value?.click()
}

// 重置音频上传
const resetAudioUpload = () => {
  if (previewAudio.value?.url) {
    URL.revokeObjectURL(previewAudio.value.url)
  }
  previewAudio.value = null
  if (audioInputRef.value) {
    audioInputRef.value.value = ''
  }
}

// 处理音频选择
const handleAudioSelect = async (event) => {
  const file = event.target.files?.[0]
  if (!file) return

  if (!file.type.startsWith('audio/')) {
    ElMessage.error('请选择音频文件')
    return
  }

  // 获取文件格式
  const extension = file.name.split('.').pop()?.toLowerCase()
  let format = extension || 'mp3'

  const loading = ElLoading.service({
    lock: true,
    text: '上传音频中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 获取上传凭证
    const uploadResponse = await apiRequest(`${API_CONFIG.ENDPOINTS.GET_UPLOAD_CREDENTIAL}?format=${format}`, {
      method: 'GET'
    })

    if (uploadResponse.code !== 200) {
      throw new Error(uploadResponse.message || '获取上传凭证失败')
    }

    const { uploadUrl, fileId } = uploadResponse.data

    // 上传到S3
    await axios.put(uploadUrl, file, {
      headers: {
        'Content-Type': file.type
      }
    })

    // 设置预览
    previewAudio.value = {
      url: URL.createObjectURL(file),
      fileId,
      fileName: file.name,
      type: file.type,
      format
    }

    ElMessage.success('音频上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(error.message || '上传失败')
  } finally {
    loading.close()
    if (audioInputRef.value) {
      audioInputRef.value.value = ''
    }
  }
}

// 获取音色列表
const getVoiceList = async () => {
  try {
    const response = await apiRequest('/aiAvatar/voiceList', {
      method: 'GET',
      params: {
        pageNo: 1,
        pageSize: 100
      }
    })

    if (response && response.code === 200 && response.data) {
      voiceList.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取AI音色列表失败:', error)
    ElMessage.warning('获取AI音色列表失败')
  }
}

// 返回上一步
const goBack = () => {
  router.push('/marketing-video/prepare')
}

// 处理视频生成
const handleGenerateVideo = async () => {
  if (!canProceed.value) {
    ElMessage.warning('请完善脚本内容')
    return
  }

  if (!selectedAvatar.value || !selectedImage.value) {
    ElMessage.warning('请先选择数字人和产品图片')
    return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '正在提交生成任务...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const params = {
      avatarId: selectedAvatar.value.id,
      productImageFileId: selectedImage.value.fileId,
      audioSourceFrom: scriptMode.value === 'tts' ? 1 : 0, // 0-用户上传音频，1-文本转语音
    }

    // 根据音频来源设置参数
    if (scriptMode.value === 'tts') {
      params.ttsText = scriptText.value
      if (selectedVoice.value?.voiceId) {
        params.voiceoverId = selectedVoice.value.voiceId
      }
    } else {
      params.audioFileId = previewAudio.value.fileId
    }

    if (subtitleStyle.value) {
      params.subtitleStyle = subtitleStyle.value
    }

    const response = await apiRequest('/marketingVideo/generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(params)
    })

    if (response.code === 200) {
      ElMessage.success('任务提交成功')
      // 跳转到生成列表页面
      router.push('/marketing-video/list')
    } else {
      throw new Error(response.message || '提交失败')
    }
  } catch (error) {
    console.error('生成失败:', error)
    ElMessage.error(error.message || '生成失败，请重试')
  } finally {
    loading.close()
  }
}

// 页面加载时从 localStorage 获取数据
onMounted(() => {
  const avatarData = localStorage.getItem('marketingAvatar')
  const imageData = localStorage.getItem('marketingImage')
  
  if (avatarData) {
    selectedAvatar.value = JSON.parse(avatarData)
  }
  
  if (imageData) {
    selectedImage.value = JSON.parse(imageData)
  }
  
  getVoiceList()
})
</script>

<style scoped>
.marketing-video-audio {
  min-height: 100vh;
  background: #18181c;
  padding: 24px;
  color: #fff;
}

.progress-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40px;
  padding: 0 100px;
}

.step-item {
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
  flex: 1;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2a2a2a;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  z-index: 2;
}

.step-item.active .step-number {
  background: #409eff;
}

.step-item.completed .step-number {
  background: #67c23a;
}

.step-text {
  color: #909399;
}

.step-item.active .step-text,
.step-item.completed .step-text {
  color: #fff;
}

.main-content {
  display: flex;
  gap: 32px;
}

.left-panel {
  width: 400px;
  background: #23232a;
  border-radius: 16px;
  padding: 24px;
}

.selected-info h3 {
  margin: 0 0 20px;
  font-size: 18px;
  color: #fff;
}

.info-cards {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-card {
  background: #18181c;
  border-radius: 12px;
  padding: 16px;
}

.info-card h4 {
  margin: 0 0 12px;
  font-size: 14px;
  color: #909399;
}

.avatar-preview,
.image-preview {
  display: flex;
  align-items: center;
  gap: 12px;
}

.avatar-preview img,
.image-preview img {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
}

.no-selection {
  color: #909399;
  text-align: center;
  padding: 20px 0;
}

.script-panel {
  flex: 1;
  background: #23232a;
  border-radius: 16px;
  padding: 24px;
  display: flex;
  flex-direction: column;
}

.script-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.script-header h3 {
  margin: 0;
  font-size: 18px;
  color: #fff;
}

.script-textarea {
  flex: 1;
  margin-bottom: 20px;
}

.audio-upload-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

.file-input {
  display: none;
}

.upload-placeholder {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #2a2a2a;
  border-radius: 12px;
  cursor: pointer;
  color: #909399;
  transition: all 0.3s ease;
}

.upload-placeholder:hover {
  border-color: #409eff;
  background: #18181c;
}

.upload-text {
  font-size: 16px;
  margin-top: 12px;
}

.upload-hint {
  font-size: 12px;
  opacity: 0.7;
  margin-top: 8px;
}

.audio-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.audio-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #fff;
}

.audio-player {
  width: 100%;
  max-width: 400px;
}

.script-footer {
  display: flex;
  gap: 12px;
  align-items: center;
}

.voice-select,
.subtitle-select {
  flex: 1;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

:deep(.el-button) {
  background: #23232a !important;
  border-color: #2a2a2a !important;
}

:deep(.el-button:hover) {
  background: #2a2a2a !important;
  border-color: #409eff !important;
}

:deep(.el-button--primary) {
  background: #409eff !important;
  border-color: #409eff !important;
}

:deep(.el-button--primary:hover) {
  background: #66b1ff !important;
  border-color: #66b1ff !important;
}

:deep(.el-button--danger) {
  background: #f56c6c !important;
  border-color: #f56c6c !important;
}

:deep(.el-button--danger:hover) {
  background: #f78989 !important;
  border-color: #f78989 !important;
}

:deep(.el-textarea__inner) {
  background: #18181c !important;
  border-color: #2a2a2a !important;
  color: #fff !important;
}

:deep(.el-select) {
  background: #18181c !important;
}

:deep(.el-select .el-input__inner) {
  background: #18181c !important;
  border-color: #2a2a2a !important;
  color: #fff !important;
}
</style> 